package com.abso.mp3tunes.locker.ui.dnd;

import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;

/**
 * A custom transfer used to drag and drop a tree selection into the music
 * player view.
 */
public class LockerTransfer extends ByteArrayTransfer {

	/** The name of the transfer. */
	private static final String TYPE_NAME = "LockerViewerTransfer"
			+ System.currentTimeMillis();

	/** The type identifier. */
	private static final int TYPE_ID = registerType(TYPE_NAME);

	/** The shared instance. */
	public static final LockerTransfer INSTANCE = new LockerTransfer();

	/** Stored object. */
	private Object object;

	/** The transfer start time. */
	private long startTime;

	/** Private constructor (don't instatiate). */
	private LockerTransfer() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.swt.dnd.Transfer#getTypeIds()
	 */
	protected int[] getTypeIds() {
		return new int[] { TYPE_ID };
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.swt.dnd.Transfer#getTypeNames()
	 */
	protected String[] getTypeNames() {
		return new String[] { TYPE_NAME };
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.swt.dnd.ByteArrayTransfer#javaToNative(java.lang.Object,
	 *      org.eclipse.swt.dnd.TransferData)
	 */
	public void javaToNative(Object object, TransferData transferData) {
		setObject(object);
		startTime = System.currentTimeMillis();
		if (transferData != null) {
			super.javaToNative(String.valueOf(startTime).getBytes(),
					transferData);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.swt.dnd.ByteArrayTransfer#nativeToJava(org.eclipse.swt.dnd.TransferData)
	 */
	public Object nativeToJava(TransferData transferData) {
		byte bytes[] = (byte[]) super.nativeToJava(transferData);
		long startTime = Long.parseLong(new String(bytes));
		return (this.startTime == startTime) ? getObject() : null;
	}

	/**
	 * Gets the current object.
	 * 
	 * @return the current object.
	 */
	public Object getObject() {
		return object;
	}

	/**
	 * Sets the current object.
	 * 
	 * @param object
	 *            the object to store.
	 */
	public void setObject(Object object) {
		this.object = object;
	}

}
